/**
 * body
 */

import React from 'react';
import PersonalContainer from '../PersonalContainer/PersonalContainer.jsx';
import PersonalSection from  '../PersonalSection/PersonalSection.jsx';
import PersonalWallpaper from '../PersonalWallPaper/PersonalWallPaper.jsx';
import PersonalMainComponent from  '../PersonalMainComponent/PersonalMainComponent.jsx';

function getCookie(name)
{
    var arr,reg=new RegExp("(^| )"+name+"=([^;]*)(;|$)");
    if(arr=document.cookie.match(reg))
        return unescape(arr[2]);
    else
        return null;
}

class PersonalBody extends React.Component {
    constructor(props) {
        super(props)

        this.limit = 5

        // todo : 给评论和笔记加上分页
        // todo : 设置可以修改
        // histories
        var cachedHistories = this.props.histories
        var totalPage = cachedHistories.length % this.limit == 0 ? parseInt(cachedHistories.length / this.limit) : parseInt(cachedHistories.length / this.limit) + 1
        var page = 1
        var displayHistories = cachedHistories.slice((page - 1) * this.limit,page * this.limit)

        this.state = {
            totalPage,
            page,
            histories : displayHistories,
            collectedCourses : this.props.collectCoursesData,
            notes : this.props.notes,
            comments : this.props.comments
        }
    }

    /**
     * 改变页数
     * @param page
     */
    changePage(page){
        var newHistories = Array.prototype.concat.call(this.props.histories,[])
        var displayHistories = newHistories.slice((page - 1) * this.limit,page * this.limit)
        this.setState({
            page : page,
            histories : displayHistories
        })
        this.forceUpdate()
    }

    /**
     * 删除历史
     * @param historyId
     */
    delHistory(historyId) {
        var displayHistories = Array.prototype.concat.call(this.state.histories, [])
        var idx = -1
        for(var i=0;i < displayHistories.length ; i++){
            if(displayHistories[i].id == historyId){
                idx = i
                break
            }
        }
        if(idx !== -1){

            var LoginToken = getCookie("LoginToken")
            fetch("/education/user/history/del",{
                method: 'POST',
                body:   JSON.stringify({
                    LoginToken,
                    historyId
                }),
                headers: { 'Content-Type': 'application/json' },
                credentials : "same-origin"
            })
                .then(res => res.json())
                .then(json => {
                    if(json.status !== 200){
                        toastr.error("后台错误，删除失败")
                        return
                    }

                    displayHistories.splice(idx,1)
                    this.setState({
                        histories : displayHistories
                    })
                    toastr.success("删除成功")
                }).catch(err => {
                    if(err){
                        toastr.error("后台错误，删除失败")
                    }
            })
        }
    }

    requestCollectCourse(historyId,callback){
        var LoginToken = getCookie("LoginToken")
        fetch("/education/user/course/collect",{
            method: 'POST',
            body:   JSON.stringify({
                LoginToken,
                historyId
            }),
            headers: { 'Content-Type': 'application/json' },
            credentials : "same-origin"
        })
            .then(res => res.json())
            .then(json => {
                if(json.status !== 200){
                    toastr.error("收藏请求失败")
                    return
                }

                callback()
            }).catch(err => {
                if(err){
                    toastr.error("收藏请求失败")
                }
        })
    }

    /**
     * 收藏课程
     * @param historyId
     * @param course
     */
    collectCourse(historyId,course){
        var self = this
        this.requestCollectCourse(historyId,() => {
            var newCollectCourse = Array.prototype.concat.call(self.state.collectedCourses,[])
            var newDisplayHistories = Array.prototype.concat.call(self.state.histories,[])

            for(var h of newDisplayHistories){
                if(h.id == historyId){
                    h.isCollect = 1
                }
            }
            newCollectCourse.push(course)
            self.setState({
                collectedCourses : newCollectCourse,
                histories : newDisplayHistories
            })
            toastr.success("收藏成功")
        })

    }

    /**
     * 取消收藏课程
     */
    unCollectCourse(historyId,course){
        var self = this
        this.requestCollectCourse(historyId,() => {
            var newCollectCourse = Array.prototype.concat.call(self.state.collectedCourses,[])
            var newDisplayHistories = Array.prototype.concat.call(self.state.histories,[])
            for(var h of newDisplayHistories){
                if(h.id == historyId){
                    h.isCollect = 0
                }
            }

            var idx = -1
            for(var i = 0; i < newCollectCourse.length; i++){
                if(newCollectCourse[i].id == course.id){
                    idx = i
                    break
                }
            }
            if(idx !== -1){
                newCollectCourse.splice(idx,1)
            }

            self.setState({
                collectedCourses : newCollectCourse,
                histories : newDisplayHistories
            })
            toastr.success("取消收藏成功")
        })

    }

    render() {
        const changePage = this.changePage.bind(this)
        const delHistory = this.delHistory.bind(this)
        const collectCourse = this.collectCourse.bind(this)
        const unCollectCourse = this.unCollectCourse.bind(this)

        return (
            <PersonalContainer fluid={true}>
                <PersonalSection>
                    <PersonalContainer fluid={true}>
                        <PersonalWallpaper avatar={this.props.avatar} username={this.props.username} sign={this.props.sign}/>
                    </PersonalContainer>
                </PersonalSection>
                <PersonalSection>
                    <PersonalMainComponent totalPage={this.state.totalPage}
                                           page={this.state.page}
                                           changePage={changePage}
                                           delHistory={delHistory}
                                           collectCourse={collectCourse}
                                           unCollectCourse={unCollectCourse}
                                           histories={this.state.histories}
                                           collectedCourses={this.state.collectedCourses}
                                           notes={this.state.notes}
                                           comments={this.state.comments}
                                           username={this.props.username}
                                           sign={this.props.sign}
                    />
                </PersonalSection>
            </PersonalContainer>
        )
    }
}

PersonalBody.displayName = 'PersonalBody';

export default PersonalBody;